#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include <fcntl.h>
#include "create_database.h"

int init_database(sqlite3 **db)
{  
    //sqlite3  *db=NULL;      
    char    *zErrMsg = NULL;
    int     rc;
    int     len;
    //述创建数据库中表的信息 
    char    *sql ="create table if not exists temperature(SN INTEGER PRIMARY KEY AUTOINCREMENT,\
                                        ID char(10), datetime char(50), temperature  char(10))";
    /*  Open database  若没有则创建*/
    len = sqlite3_open(database_name, db);
    if(len != SQLITE_OK)
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(*db));                               
        return  -1; 
    }
    printf("Opened database successfully\n");
    
    /* 插入表时判断表是否存在，不存在则创建00 */
    rc = sqlite3_exec(*db, sql, 0, 0, &zErrMsg);
    if( rc != SQLITE_OK )
    {
        sqlite3_close(*db);
        fprintf(stderr, "Create table error: %s and close database.\n", zErrMsg);
        return -1; 
    }
    printf("Table created successfully\n");
    
    return 0;
}



int insert_database(sqlite3 *db, analy_data* data)
{
    char    sql1[128];
    int     ret;
    char    *zErrMsg = NULL;

    memset(sql1, 0, sizeof(sql1));
    //插入表的形式   "create table temperature(ID char(10), datetime char(50), temperature  char(10))";
    //插入值    "insert into temperature(id, datatime) values('%s', '%s');"
    snprintf(sql1, 128, "insert into temperature values(NULL, '%s', '%s', '%s');" ,
            data->id_buf, data->time_buf, data->temper_buf);
    //保证了数组sql1的内容为字符串
    sql1[127] = '\0';    
    printf("%s\n", sql1); 
    
    //调用sqlite3_exec()；将数据存储至temperature表中
    ret = sqlite3_exec(db, sql1, 0 , 0, &zErrMsg);
    if (ret != SQLITE_OK)     //判断返回值，如果不等于SQLITE_OK，即插入记录失败                
    {   
        sqlite3_close(db);
        printf("insert data failure: %s.\n", zErrMsg);   
        return -1;
    }
    //暂时不关闭数据库
    return 0;
}

